package hotel.action;

import hotel.data.MD5Creator;
import hotel.form.RegistrateForm;
import hotel.service.ServiceManager;
import hotel.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
 * This class create new user
 * There are doesn't matter witch language used
 * name, surname, username and password may have different languages
 * In DataBase password lay like hash sum of password that user typed 
 * @author Alex
 *
 */
public class RegistrateAction extends Action 
{
	private static final Logger logger = Logger.getLogger(RegistrateAction.class);
	private static final String REGISTRATEACTION_ERROR = "Error in RegistrateAction:";
	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception 
    {
		String mapper = ForwardActionTo.ERROR;

		try
		{
	    RegistrateForm registrateForm = (RegistrateForm)form;
			if (registrateForm != null) 
		     {
				if (registrateForm.getPassword() != null)
				{
			    	UserService userService = ServiceManager.getDefault().getUserService();
			        userService.insertUser(
			        		registrateForm.getUsername(),
			        		MD5Creator.MD5(registrateForm.getPassword()),
			        		registrateForm.getName(),
			        		registrateForm.getSurname());
			        
			        mapper = ForwardActionTo.SUCCESS;
				}
		     }
		 }
		 catch(NullPointerException e)
		 {
	 		 logger.error(REGISTRATEACTION_ERROR + e);
	 	 }
		
		return mapping.findForward(mapper);
    }
}
